package com.example.permissiondispatcher

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import permissions.dispatcher.PermissionRequest
import permissions.dispatcher.ktx.withPermissionsCheck

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        findViewById<Button>(R.id.call).setOnClickListener {
            call()
        }
    }

    /**
     * 需要权限的方法
     */
    private fun call() = withPermissionsCheck(
        Manifest.permission.CALL_PHONE,
        onShowRationale = ::showWhy,
        onPermissionDenied = ::showDenied,
        onNeverAskAgain = ::showNotAsk) {
        val intent = Intent(Intent.ACTION_CALL)
        val data = Uri.parse("tel:10086")
        intent.data = data
        try {
            startActivity(intent)
        } catch (e: SecurityException) {
            e.printStackTrace()
        }
    }

    /**
     * 提示用户为什么要开始权限
     */
    private fun showWhy(request: PermissionRequest) {
        AlertDialog.Builder(this).setMessage("提示用户为何需要开启这个权限")
            .setPositiveButton("我知道了") { _, _ ->
                request.proceed()  // 再次执行权限请求
            }.show()
    }

    /**
     * 用户选择拒绝时提示
     */
    private fun showDenied() {
        ToastUtil.showShort(this, "用户拒绝时提示")
    }

    /**
     * 用户选择不再询问后提示
     */
    private fun showNotAsk() {
        AlertDialog.Builder(this).setMessage("该功能需要访问电话权限,不开启将无法正常工作!")
            .setPositiveButton("确定") { _, _ ->

            }.show()
    }

}
